//---------------------------------------controller------------------------------------------------
var isPersonShow=false;
var selectPerson=-1;//选择的人物ID
var selectLayer=null;//选择人物层
var lastX=0;
var lastY=0;
var outSbbhList="";
function showHidePerson(){
    isPersonShow=!isPersonShow;
    if(isPersonShow){
        init();
    }else{
        removeAllPerson();
        //去掉选中的人物
        selectPerson=-1;
        doSelectedPerson(selectPerson,false);
    }
}

$(function() {
    getOutSbbh();
});

//获取出区的设备编号，该设备编号不显示人员
function getOutSbbh() {
    $.ajax({
        type: "POST",
        url: "getOutSbbh",
        contentType: "application/json; charset=utf-8",
        async:false,
        success: function(data){
            if(data){
                outSbbhList=data.resObject;
            }
        },
        error: function(ex){
           // alert("系统异常！");
        }
    });
}

// 初始化人员数据
function init() {
    // 初始人员
    loadPersons();
    if(isPersonShow){
        setTimeout(function(){
            init();
        },3000)
    }

}

//储存所有id对应feature的名值对
var personArray = new Array();


// 人物放入Array
function push2Array(pd) {
    var p = getPerson(pd.id);
    if (null == p) {
        p = new Object();
        p.id = pd.id;
        p.name = pd.name;
        p.type = pd.type;
        p.x = pd.currentX;
        p.y = pd.currentY;
        lastX=pd.currentX;
        lastY=pd.currentY;
        p.sbbh=pd.sbbh;
        p.feature = null;//图层

        if(outSbbhList && outSbbhList.indexOf(pd.sbbh)>=0){
            //指定位置定位不显示
            p.isShow=false;
        }else{
            p.isShow=true;
        }

        personArray.push(p);
    } else {
        p.x = pd.currentX;
        p.y = pd.currentY;
        lastX=pd.currentX;
        lastY=pd.currentY;
        p.sbbh=pd.sbbh;
        p.type = pd.type;
        if(outSbbhList && outSbbhList.indexOf(pd.sbbh)>=0){
            //指定位置定位不显示
            p.isShow=false;
        }else{
            p.isShow=true;
        }
    }
    p.index = 0;//是否移动过,0未移动，1已移动
}

function setUnShowAll(){
    for (var i = 0; i < personArray.length; i++) {
        personArray[i].isShow=false;
    }
}
// 根据ID获取人员数据
function getPerson(id) {
    for (var i = 0; i < personArray.length; i++) {
        if (personArray[i].id == id) {
            return personArray[i];
        }
    }
    return null;
}

function moveAllPersons() {
    // 每个人物单独创建图层，减少刷新
    for (var i = 0; i < personArray.length; i++) {
        movePerson(personArray[i].id,personArray[i].type);
        //人物选择
        if(selectPerson==personArray[i].id){
            doSelectedPerson(selectPerson,true);
        }
    }
}

// 移动人物
function movePerson(id,type) {
    var p = getPerson(id);

    if (p && p.x && p.y) {
        // 一旦有坐标检查是否有人物显示层
        var pLayer = p.feature;
        if (!pLayer) {
            if(!p.isShow){
                //
                return;
            }
            pLayer = new ol.layer.Vector({
                source : new ol.source.Vector({})
            });

            map.addLayer(pLayer);
            p.feature = pLayer;
        }else if(!p.isShow){
            map.removeLayer(pLayer);
            p.feature=null;
            return;
        }
        if (p.index > 0) {//已经移动过
            return;
        }
        // 根据坐标集合和当前index一步步刷人物坐标
        // console.info(p.name,p.xys[p.index].x,p.xys[p.index].y);
        // var
        // ptransform=ol.proj.transform([p.xys[p.index].x,p.xys[p.index].y],'EPSG:4326',
        // 'EPSG:3857');
        var ptransform = ol.proj.transform(
            [ p.x, p.y ], 'EPSG:4326',
            'EPSG:4326');

        // ol.proj.transform([p.xys[p.index].x,p.xys[p.index].y],'EPSG:4326',
        // 'EPSG:3857');
        var currentPoint = new ol.geom.Point(ptransform);

        var pstyle = new ol.style.Style({
            text : new ol.style.Text({ // 文本样式
                font : '14px Calibri,sans-serif',
                fill : new ol.style.Fill({
                    color : '#000'
                }),
                stroke : new ol.style.Stroke({
                    color : '#fff',
                    width : 3
                }),
                offsetX : -5,
                offsetY : 25
            }),
            image : new ol.style.Icon(/** @type {olx.style.IconOptions} */
                ({

                    opacity : 0.95,
                    src : $("#contextPath").val()+'/userfiles/points/person/32X32/32X32-17-' + type + '.png'
                }))
        });
        pstyle.getText().setText(p.name);
        var feature = new ol.Feature(currentPoint);
        pLayer.getSource().clear();
        pLayer.getSource().addFeature(feature);
        pLayer.setStyle(pstyle);
        // console.info(feature);
        // 移动结束
        p.index = p.index + 1;
    }
}

function doSelectedPerson(id,isSelected){
//	console.info(id);
    //TODO
    if(!isSelected){
        //不选择
        if(selectLayer){
            //移除
            map.removeLayer(selectLayer);
            selectLayer=null;
        }
    }else{
        var p = getPerson(id);
        if(!selectLayer && p.isShow){
            if(p.isShow){
                //添加
                selectLayer = new ol.layer.Vector({
                    source : new ol.source.Vector({})
                });
                map.addLayer(selectLayer);
            }
        }else if(!p.isShow){
            map.removeLayer(selectLayer);
            selectLayer=null;
            return ;
        }
//		console.info(selectLayer);

        if (p && p.x && p.y){
            var ptransform = ol.proj.transform(
                [ p.x, p.y ], 'EPSG:4326',
                'EPSG:4326');

            var currentPoint = new ol.geom.Point(ptransform);

            var pstyle = new ol.style.Style({
                image : new ol.style.Icon(/** @type {olx.style.IconOptions} */
                    ({

                        opacity : 0.95,
                        opacity : 0.95,
                        opacity : 0.95,
                        opacity : 0.95,
                        src : $("#contextPath").val()+'/userfiles/points/person/selected2.gif'
                    }))
            });
            var feature = new ol.Feature(currentPoint);
            selectLayer.getSource().clear();
            selectLayer.getSource().addFeature(feature);
            selectLayer.setStyle(pstyle);
        }
    }
}

function removeAllPerson(){
    for (var i = 0; i < personArray.length; i++) {
        map.removeLayer(personArray[i].feature);
    }
    personArray = new Array();
}

function move() {
    for (var i = 0; i < 60; i++) {
        setTimeout(function() {
            moveFeature2();
        }, 1000 * i)
    }
}
//---------------------------------------websocket------------------------------------------------
var websocket = null;
var wensocketIsOpen=false;
function openWebSocket(type){
    //personId=id;
    //判断当前浏览器是否支持WebSocket，支持就创建连接，不支持就提示
    if(isSupportWebSocket()){
        listenerWebSocket(type);
        //showWebSocketInfo();
    }
}


//监听wensocket的回调方法
function listenerWebSocket(type){
    //连接发生错误的回调方法
    websocket.onerror = function () {
        //setMessageInnerHTML("WebSocket连接发生错误!");
    };

    //连接成功建立的回调方法
    websocket.onopen = function () {
        //setMessageInnerHTML("WebSocket连接成功");
        //websocket.send("socket建立连接成功，测试消息。。。");
        var jsonObject={};
        jsonObject["type"]=type;
        jsonObject["mapId"]=currentSelectTiles.id;
        var jsonInfo=JSON.stringify(jsonObject);
        websocket.send(jsonInfo);
        wensocketIsOpen=true;
    }

    //接收到消息的回调方法
    websocket.onmessage = function (event) {
        setUnShowAll();//先将列表所有设置成不显示
        var arrayData=JSON.parse(event.data);
        //if(lastX==0 && lastY==0){
            // setMessageInnerHTML(event.data);
            //removeAllPerson();//先移除所有
            for (var i = 0; i < arrayData.length; i++) {
                push2Array(arrayData[i]);
            }
            moveAllPersons();

        // }else{
        //     removeAllPerson();
        //     removeAllMove();
        //     isMoveShow=true;
        //     var pd=new Object();
        //     for (var i = 0; i < arrayData.length; i++) {
        //         pd=arrayData[i];
        //     }
        //     var locationSteps=new Array();
        //     //上一次位置
        //     var lastPoint=new Object();
        //     lastPoint.id = pd.id;
        //     lastPoint.name = pd.name;
        //     lastPoint.type = pd.type;
        //     lastPoint.x = lastX;
        //     lastPoint.y = lastY;
        //     locationSteps.push(lastPoint);
        //     //当前位置
        //     var currentPoint=new Object();
        //     currentPoint.id = pd.id;
        //     currentPoint.name = pd.name;
        //     currentPoint.type = pd.type;
        //     currentPoint.x = pd.currentX;
        //     currentPoint.y = pd.currentY;
        //     locationSteps.push(currentPoint);
        //     move_step=locationSteps;
        //     if(pd.type==1){
        //         personName=pd.name;
        //     }else if(pd.type==2){
        //         personName=pd.name;
        //     }
        //     addmoveLine(personId,pd.type);
        //     lastX=currentPoint.x;
        //     lastY=currentPoint.y;
        // }
    }

    //连接关闭的回调方法
    websocket.onclose = function () {
        //setMessageInnerHTML("WebSocket连接关闭!");
    }

    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function () {
        closeWebSocket();
    }
}
function doSelectedPerson(id,isSelected){
//	console.info(id);
    //TODO
    if(!isSelected){
        //不选择
        if(selectLayer){
            //移除
            map.removeLayer(selectLayer);
            selectLayer=null;
        }
    }else{
        var p = getPerson(id);
        if(!selectLayer && p.isShow){
            if(p.isShow){
                //添加
                selectLayer = new ol.layer.Vector({
                    source : new ol.source.Vector({})
                });
                map.addLayer(selectLayer);
            }
        }else if(!p.isShow){
            map.removeLayer(selectLayer);
            selectLayer=null;
            return ;
        }
//		console.info(selectLayer);

        if (p && p.x && p.y){
            var ptransform = ol.proj.transform(
                [ p.x, p.y ], 'EPSG:4326',
                'EPSG:4326');

            var currentPoint = new ol.geom.Point(ptransform);

            var pstyle = new ol.style.Style({
                image : new ol.style.Icon(/** @type {olx.style.IconOptions} */
                    ({
                        opacity : 0.95,
                        src :  $("#contextPath").val()+'/points/person/selected2.gif'
                    }))
            });
            var feature = new ol.Feature(currentPoint);
            selectLayer.getSource().clear();
            selectLayer.getSource().addFeature(feature);
            selectLayer.setStyle(pstyle);
        }
    }
}

function showWebSocketInfo(){
    if(websocket!=null){
        setMessageInnerHTML("websocket="+JSON.stringify(websocket));
        setMessageInnerHTML("CONNECTING="+websocket.CONNECTING);//0
        setMessageInnerHTML("OPEN="+websocket.OPEN); //1
        setMessageInnerHTML("CLOSING="+websocket.CLOSING); //2
        setMessageInnerHTML("CLOSED="+websocket.CLOSED); //3
    }
}

//判断当前浏览器是否支持WebSocket
function isSupportWebSocket(){
    if ('WebSocket' in window) {
        //websocket = new WebSocket("ws://127.0.0.1:8081/dingwei/websocket/mysocket");
        websocket = new WebSocket('ws://'+$("#basePath").val()+'/websocket/mysocket');
        return true;
    }else {
        alert('当前浏览器 不支持websocket');
        return false;
    }
}

//将消息显示在网页上
function setMessageInnerHTML(innerHTML){
    // document.getElementById('message').innerHTML += innerHTML + '<br/>';
    console.info(innerHTML);
}
//关闭socket
function closeWebSocket() {
    if(websocket!=null && wensocketIsOpen){
        websocket.close();
        showWebSocketInfo();
        websocket=null;
        wensocketIsOpen=false;
    }
    setMessageInnerHTML("websocket已关闭！");
}
//清空message
function clear(){
    document.getElementById('message').innerHTML="";
    setMessageInnerHTML("清空message！");
}

//发送消息
function sendMessage() {
    var message = document.getElementById('text').value;
    if(wensocketIsOpen){//如果socket开启
        websocket.send(message);
    }else{
        setMessageInnerHTML("websocket未创建或已关闭，请先开启连接！");
    }
}